import { IconFont, IconType } from '@/components/AntdIcon';
import { Flex, Modal, message } from 'antd';
import { useEffect, useState } from 'react';
import CopyToClipboard from 'react-copy-to-clipboard';
import { useModel } from 'umi';
import { Button as ToolBarButton } from './Button';
import { Button } from 'antd';

const title = '板件数据复制';

export function PlankEditor() {
  const { plank, setPlank } = useModel('bom');
  const [plankDataModalVisible, setPlankDataModalVisible] = useState(false);
  const [tempJson, setTempJson] = useState<string>('');
  const plankDataJSON = JSON.stringify(plank, null, 4);

  useEffect(() => {
    setTempJson(plankDataJSON);
  }, [plankDataJSON]);

  return (
    <span>
      <ToolBarButton
        icon={<IconFont type={IconType.Edit} />}
        onClick={() => setPlankDataModalVisible(true)}
      >
        {title}
      </ToolBarButton>
      <Modal
        title={
          <Flex align="center" justify="space-between">
            {title}
            <CopyToClipboard
              text={plankDataJSON}
              onCopy={() => message.success('复制成功')}
            >
              <Button className="mr-4">复制</Button>
            </CopyToClipboard>
          </Flex>
        }
        open={plankDataModalVisible}
        footer={false}
        onCancel={() => {
          try {
            const data = JSON.parse(tempJson);
            // setPlank(data);
            setPlankDataModalVisible(false);
          } catch (error) {
            alert('JSON解析失败，请检测JSON格式是否正确');
          }
        }}
      >
        <textarea
          readOnly
          style={{
            width: '100%',
            height: 200,
          }}
          value={tempJson}
          onChange={(e) => {
            const json = e.target.value; // setPlankData(JSON.parse(json));

            setTempJson(json);
          }}
        />
      </Modal>
    </span>
  );
}
